// pages/medicine/medicine.js
const MedicinePostUrl = require("../../config.js").medicinePostUrl

const MedicineRecipeUrl = require("../../config.js").medicineRecipeUrl

function copyobj(a) {
  var c = {};
  c = JSON.parse(JSON.stringify(a));
  return c;
}

function getTakeInValue(value){
  switch(value){
    case "0": return [true, true];
    case "1": return [false, true];
    case "2": return [true, false];
    case "3": return [false, false];
    case "4": return [false, false];
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    medicineList:[

    ],
    radioItems: [
      { name: '按时按量服用', value: '0', checked: true  },
      { name: '按时未按量服用', value: '1'},
      { name: '按量未按时服用', value: '2'},
      { name: '未按时未按量但服用', value: '3'},
      { name: '未服用', value:'-1'}
    ],
    otherMedicineList:[

    ],
    //样本id，处方类型：出诊、复诊，处方id
    sampleID: null, 
    recipeType: null, 
    recipeID: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var medicine_list = []
   
    wx.getStorage({
      key: 'other_medicine_list',
      success: function (res) {
        that.setData({
          otherMedicineList: res.data
        })
      },
    })
    
    //获取处方
    var token = wx.getStorageSync("token")
    wx.request({
      url: MedicineRecipeUrl,
      method:'GET',
      header: {
        'Authorization': "Token " + token
      },
      success:function(res){
        var result = res.data.result;
        var sample_id, recipe_type, recipe_id;
        for(var i = 0; i < result.length;i++){
          sample_id = res.data.sample_id;
          recipe_type = res.data.recipe_type;
          recipe_id = res.data.recipe_id;
          medicine_list.push({
            recipe_drug_id: result[i].recipe_drug_id,
            drug_id: result[i].drug_id,
            drug_name: result[i].drug_name,
            drug_path: result[i].drug_path.split('\t')[1],
            drug_dose: result[i].drug_dose,
            drug_unit: result[i].drug_unit.split('\t')[1],
            take_time: result[i].drug_freq.split('\t')[1],
            radioItems: copyobj(that.data.radioItems)
          })
        }

        that.setData({
          medicineList: medicine_list,
          sampleID:sample_id,
          recipeType: recipe_type,
          recipeID: recipe_id
        })
      }

    })
    
  },
  onShow: function(e){
    var that = this
    console.log("页面返回")
    wx.getStorage({
      key: 'other_medicine_list',
      success: function (res) {
        that.setData({
          otherMedicineList: res.data
        })
      },
    })
  },
  radioChange: function (e) {
    console.log('radio发生change事件，target值为：', e.target.id, "携带value值为：", e.detail.value);

    var target_id = e.target.id;
    var radioItems = this.data.medicineList[target_id].radioItems;
    var medicineList = this.data.medicineList;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }
    this.setData({
      medicineList: this.data.medicineList
    });
  },
  radioChange2: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);

    var radioItems = this.data.radioItems2;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
      radioItems2: radioItems
    });
  },
  addMedicine: function(e){
    wx.navigateTo({
      url: '../other-medicine/other-medicine',
    })
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    var data = {};
    data['sample_id'] = this.data.sampleID;
    data['recipe_type'] = this.data.recipeType;
    data['recipe_id'] = this.data.recipeID;

    data['user_comment'] = e.detail.value.user_comment;
    
    var other_medicine = wx.getStorageSync("other_medicine_list");
    data['recipe_drugs_other'] = other_medicine;

    var take_recoeds = []
    for (var item in e.detail.value) {
      if (item.split('-')[0] == 'recipe') {
        var recipe_id = item.split('-')[1];
        var drug_id = item.split('-')[2];
        var value = e.detail.value[item];
        var take_value = getTakeInValue(value);
        take_recoeds.push({
          recipe_drug_id: recipe_id,
          drug_id: drug_id,
          drug_in_dose: take_value[0],
          drug_in_time: take_value[1]
        })
      }
    }
    data['recipe_drugs'] = take_recoeds;
    console.log(data);
    data['overwrite'] = true;
    var token = wx.getStorageSync("token");
    wx.request({
      url: MedicinePostUrl,
      method: 'POST',
      header: {
        'Authorization': "Token " + token
      },
      data: data,
      success: function(res){
        wx.navigateBack({
          
        })
      }
    })
    
  },
  del_other_medicine: function(e){
    var index = e.target.dataset.index;
    var other_medicine_list = wx.getStorageSync("other_medicine_list");
    other_medicine_list.splice(index, 1)
    wx.setStorage({
      key: 'other_medicine_list',
      data: other_medicine_list,
    })
    this.setData({
      otherMedicineList: other_medicine_list
    })
  } 
})